package com.CommunityHub.kiana.controller;
import com.CommunityHub.kiana.po.ResidenceInfo;
import com.CommunityHub.kiana.po.ServiceRecord;
import com.CommunityHub.kiana.po.User;
import com.CommunityHub.kiana.service.MemberService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/ServiceRequestServlet")
public class ServiceRequestServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        User user = (User) session.getAttribute("user");
        int memberId = user.getId();

        MemberService memberService = new MemberService();
        try {
            // 获取会员的所有入住人
            List<ResidenceInfo> occupants = memberService.getOccupants(memberId);
            request.setAttribute("occupants", occupants);

            request.getRequestDispatcher("serviceRequest.jsp").forward(request, response);
        } catch (SQLException e) {
            request.setAttribute("error", "加载入住人失败: " + e.getMessage());
            request.getRequestDispatcher("serviceRequest.jsp").forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 获取表单参数
        int residenceId = Integer.parseInt(request.getParameter("residenceId"));
        String serviceType = request.getParameter("serviceType");
        String serviceDate = request.getParameter("serviceDate");
        String serviceTime = request.getParameter("serviceTime");
        int duration = Integer.parseInt(request.getParameter("duration"));
      //  String specialRequest = request.getParameter("specialRequest");

        // 组合日期时间
        Date serviceDateTime = parseDateTime(serviceDate, serviceTime);

        // 创建服务记录对象
        ServiceRecord record = new ServiceRecord();
        record.setResidenceId(residenceId);
        record.setServiceType(serviceType);
        record.setServiceTime(serviceDateTime);
        record.setServiceDuration(duration);
        record.setServiceStatus(0); // 0=进行中
        //record.setSpecialRequest(specialRequest);

        // TODO: 需要分配管家ID (这里设为固定值，实际应从系统分配)
        record.setStewardId(1);

        MemberService memberService = new MemberService();
        try {
            // 重新加载入住人列表
            User user = (User) session.getAttribute("user");
            List<ResidenceInfo> occupants = memberService.getOccupants(user.getId());
            request.setAttribute("occupants", occupants);

            if (memberService.requestService(record)) {
                // 设置成功标志和消息
                request.setAttribute("success", true);
                request.setAttribute("message", "服务申请已成功提交！");
            } else {
                request.setAttribute("error", "服务申请提交失败");
            }
        } catch (SQLException e) {
            request.setAttribute("error", "系统错误: " + e.getMessage());
        }

        // 转发回原页面
        request.getRequestDispatcher("ServiceHistoryServlet").forward(request, response);
    }

    // 辅助方法：解析日期时间
    private Date parseDateTime(String dateStr, String timeStr) {
        try {
            String dateTimeStr = dateStr + " " + timeStr;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.parse(dateTimeStr);
        } catch (ParseException e) {
            return new Date();
        }
    }
}